#!/usr/bin/env node

const readline = require("readline-sync");
const api = require("./api");

let mainHandlers = new Map();

mainHandlers.set("m", () => {
  console.log("r get requirements");
  console.log("p get projects");
  console.log("q quit");
});

mainHandlers.set("r", async () => {
  let requirements = await api.getRequirements();
  if (requirements !== {}) {
    requirements.forEach(requirement => {
      console.log(`${requirement.requirementNo}: ${requirement.name}`);
    });
    console.log("input requirementNo to view details of that requirement");
    console.log("input n to create a new requirement");
    console.log("input q to upper menu");
    const command = readline.question("@requirement: ");
    if (command === "n") {
      const requirementNo = readline.question("requirement no: ");
      const requirementName = readline.question("name: ");
      const description = readline.question("description: ");
      const requirementRequest = {
        requirementNo: requirementNo,
        name: requirementName,
        description: description
      };
      let result = await api.addRequirement(requirementRequest);
      console.log(result);
    } else if (command !== "q") {
      const requirementDetail = await api.getRequirementDetail(command);
      if (requirementDetail !== {}) {
        console.log(`no: ${requirementDetail.requirementNo}`);
        console.log(`name: ${requirementDetail.name}`);
        console.log(`description: ${requirementDetail.description}`);
        console.log(`createTime: ${requirementDetail.createTime}`);
        console.log(`updateTime: ${requirementDetail.updateTime}`);
        console.log(`version: ${requirementDetail.version}`);
      }
    }
  } else {
    console.log("no requirements found");
  }
});

mainHandlers.set("p", async () => {
  let projects = await api.getProjects();
  projects.forEach(project => {
    console.log(project);
  });
});

mainHandlers.set("q", () => {
  process.exit();
});

console.log("Welcome to use storode");
console.log("input m for manual");

async function index() {
  const command = readline.question("@~: ");
  const handler = mainHandlers.get(command);
  if (handler === undefined) {
    console.log("Wrong command, please input m for manual");
  } else {
    await handler();
  }
  index();
}

index();
